package com.dc.ssjt.service.impl;

import com.dc.ssjt.entity.Order;
import com.dc.ssjt.service.AccountService;
import com.dc.ssjt.service.OrderService;
import com.dc.ssjt.service.StorageService;
import com.dc.ssjt.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * 测试门面业务逻辑
 *
 * @author duchao
 */
@Slf4j
@Service
public class TestServiceImpl implements TestService {

    private final OrderService orderService;
    private final StorageService storageService;
    private final AccountService accountService;

    public TestServiceImpl(OrderService orderService, StorageService storageService, AccountService accountService) {
        this.orderService = orderService;
        this.storageService = storageService;
        this.accountService = accountService;
    }


    /**
     * 下单
     *
     * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    @ShardingTransactionType(TransactionType.XA)
    @Override
    public void order(Order order) {

        log.info("创建订单....");
        orderService.create(order);
        log.info("订单创建完成");

        if(new Random().nextInt(2) % 2==0){
            throw new RuntimeException();
        }

        log.info("扣减库存....");
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("库存扣减完成");

        log.info("扣减账户....");
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("账户扣减完成");
    }
}
